#encoding=utf8
'''
Created on Apr 15, 2015

@author: jingyang <jingyang@smalltreemedia.com>
'''
from django.contrib import admin
from version.models import ChangeLog
from utils import field

from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_protect
from django.db import transaction

csrf_protect_m = method_decorator(csrf_protect)


class ChangeLogAdmin(admin.ModelAdmin):
    list_per_page = 20
    list_display = ('ver_num', 'update_time', 'title', 'get_content')
    change_form_template = 'version_changeform.html'
    search_fields = ('ver_num', 'title')
    exclude = ('editor',)

    @field('Content', allow_tags=True, admin_order_field='content')
    def get_content(self, obj):
        return obj.content.replace(' ', '&nbsp;').replace('\n', '<br />')

    def save_model(self, request, obj, form, change):
        if not change:
            obj.editor = request.user.email
        obj.save()

    def get_actions(self, request):
        """
        remove delete action
        """
        actions = super(ChangeLogAdmin, self).get_actions(request)
        if actions.get('delete_selected'):
            del actions['delete_selected']
        return actions

    def get_fieldsets(self, request, obj=None):
        if not self.has_add_permission(request):
            return (
                (None, {
                    'fields':
                    (
                    'ver_num',
                    'update_time',
                    'title',
                    'get_content',
                    'editor',
                    )
                }),
            )
        return admin.ModelAdmin.get_fieldsets(self, request, obj=obj)

    def get_readonly_fields(self, request, obj=None):
        if not self.has_add_permission(request):
            return ('ver_num', 'update_time', 'title', 'content', 'editor',
                'get_content')
        return admin.ModelAdmin.get_readonly_fields(self, request, obj=obj)

    @csrf_protect_m
    @transaction.commit_on_success
    def change_view(self, request, object_id, form_url='', extra_context=None):
        extra_context = {'title': 'Change Log'}
        return admin.ModelAdmin.change_view(self, request, object_id, form_url=form_url, extra_context=extra_context)

admin.site.register(ChangeLog, ChangeLogAdmin)
